package com.jkj.http.sys.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jkj.http.controller.BaseController;
import com.jkj.http.entity.LayPadding;
import com.jkj.http.entity.TreeSelect;
import com.jkj.http.interceptor.AuthorizeChecked;
import com.jkj.http.sys.entity.SysPermission;
import com.jkj.http.sys.entity.SysRole;
import com.jkj.http.sys.service.PermissionService;
import com.jkj.utils.JsonUtils;
import com.jkj.utils.OperatorProvider;
import com.jkj.utils.TreeSelectHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;


@RestController
@RequestMapping(value = "/system/permission")
public class PermissionController extends BaseController {
    @Autowired
    private PermissionService permissionService;

    /**
     * 权限列表画面
     *
     * @return
     */
    @AuthorizeChecked()
    @RequestMapping(value = "/index", method = {RequestMethod.GET})
    public ModelAndView index() {
        return new ModelAndView("system/permission/index");
    }

    /**
     * 权限列表查询（分页）
     *
     * @param pageIndex
     * @param pageSize
     * @param keyWord
     * @return
     */
    @AuthorizeChecked()
    @RequestMapping(value = "/index", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    public String index(int pageIndex, int pageSize, String keyWord) {
        int totalCount = permissionService.getTotalCount(keyWord);
        PageHelper.startPage(pageIndex, pageSize);//这行是重点，表示从pageNum页开始，每页pageSize条数据
        List<SysPermission> list = permissionService.getList2(keyWord);
        PageInfo<SysPermission> pageInfo = new PageInfo<>(list);
        List<SysPermission> pageData = pageInfo.getList();
        LayPadding<SysPermission> result = new LayPadding<SysPermission>();
        result.setResult(true);
        result.setMsg("success");
        result.setList(pageData);
        result.setCount(totalCount);
        return JsonUtils.toJSON(result);
    }

    /**
     * 权限新增或者修改页面
     *
     * @return
     */
    @AuthorizeChecked()
    @RequestMapping(value = "/form", method = {RequestMethod.GET})
    public ModelAndView form() {
        return new ModelAndView("system/permission/form");
    }

    /**
     * 插入修改权限信息
     *
     * @param session
     * @param model
     * @return
     */
    @AuthorizeChecked()
    @RequestMapping(value = "/form", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    public String form(HttpSession session, SysPermission model) {
        if (StrUtil.isEmpty(model.getId())) {
            model.setCreateUser(OperatorProvider.getCurrent(session).getAccount());
            int row = permissionService.insert(model);
            return row > 0 ? success() : error();
        } else {
            model.setModifyUser(OperatorProvider.getCurrent(session).getAccount());
            int row = permissionService.update(model);
            return row > 0 ? success() : error();
        }
    }

    /**
     * 权限详情画面
     *
     * @return
     */
    @AuthorizeChecked()
    @RequestMapping(value = "/detail", method = {RequestMethod.GET})
    public ModelAndView detail() {
        return new ModelAndView("system/permission/detail");
    }


    /**
     * 删除权限
     *
     * @param primaryKey
     * @return
     */
    @AuthorizeChecked()
    @RequestMapping(value = "/delete", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    public String delete(String primaryKey) {
        int count = permissionService.getChildCount(primaryKey);
        if (count == 0) {
            int row = permissionService.delete(primaryKey.split(","));
            return row > 0 ? success() : error();
        }
        return error("操作失败，请先删除该项的" + count + "个子级权限。");
    }

    /**
     * 根据主键得到权限信息
     *
     * @param primaryKey
     * @return
     */
    @RequestMapping(value = "/getForm", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    public String getForm(String primaryKey) {
        SysPermission entity = permissionService.get(primaryKey);
        entity.setIsEdit(entity.getIsEdit().equals("1") ? "true" : "false");
        entity.setIsEnable(entity.getIsEnable().equals("1") ? "true" : "false");
        entity.setIsPublic(entity.getIsPublic().equals("1") ? "true" : "false");
        return JsonUtils.toJSON(entity);
    }


    /**
     * 得到权限列表（下拉列表层级关系）
     *
     * @return
     */
    @RequestMapping(value = "/getParent", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    public String getParent() {
        List<SysPermission> data = permissionService.getPermissionList();
        List<TreeSelect> treeList = new ArrayList<TreeSelect>();
        for (SysPermission item : data) {
            TreeSelect model = new TreeSelect();
            model.setId(item.getId());
            model.setText(item.getName());
            model.setParentId(item.getParentId());
            treeList.add(model);
        }
        return TreeSelectHelper.ToTreeSelectJson(treeList);
    }

    /**
     * 选择图标画面
     *
     * @return
     */
    @RequestMapping(value = "/icon", method = {RequestMethod.GET})
    public ModelAndView icon() {
        return new ModelAndView("system/permission/icon");
    }
}
